package com.stars.pao.aicloud.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stars.pao.aicloud.entity.Answer;
import com.stars.pao.aicloud.entity.enums.AiModelEnum;
import com.stars.pao.aicloud.entity.enums.AiTypeEnum;
import com.stars.pao.aicloud.service.IAnswerService;
import com.stars.pao.aicloud.util.AppVariable;
import com.stars.pao.aicloud.util.ResponseEntity;
import com.stars.pao.aicloud.util.SecurityUtil;
import com.stars.pao.aicloud.util.idempotent.Idempotent;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiImageClient;
import org.springframework.ai.openai.OpenAiImageOptions;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Tag(name = "OpenAI控制器")
//openAI 大模型调用
@RestController
@RequestMapping("/openai")
public class OpenAIController {
    @Resource
    private OpenAiChatClient chatModel;

    @Resource
    private OpenAiImageClient imageModel;

    @Resource
    private IAnswerService answerService;

    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * 调用Open AI 聊天接口
     * @param question
     * @return
     */
    @Idempotent
    @PostMapping("/chat")
    public ResponseEntity chat(String question) {
        if(!StringUtils.hasLength(question)) {
//            输出内容为空
            return ResponseEntity.fail("请先输入内容");
        }
        // 执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.OPENAI.getValue(),
                AiTypeEnum.CHAT.getValue());
        String result = ""; // 大模型返回的结构
        boolean isSave = false; // 数据添加状态
        // 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                // 获取分布式锁失败
                return ResponseEntity.fail("请勿频繁请求，请稍后再试");
            }
//        调用 Open AI 接口
            result = chatModel.call(question);
//        保存数据在数据库中
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(result);
            answer.setModel(AiModelEnum.OPENAI.getValue());
            answer.setType(AiTypeEnum.CHAT.getValue());
            answer.setUid(uid);
            isSave = answerService.save(answer);
        } catch (Exception e) {
        } finally {
            // 释放锁
            rLock.unlock();
        }
        if(!isSave) {
//            保存失败
            return ResponseEntity.fail("数据保存失败，请重试");
        }
        return ResponseEntity.succ(result);
    }
    /**
     * 调用Open AI 绘图接口
     * @param question
     * @return
     */
    @Idempotent
    @PostMapping("/draw")
    public ResponseEntity draw(String question) {
        if(!StringUtils.hasLength(question)) {
//            输出内容为空
            return ResponseEntity.fail("请先输入内容");
        }
        // 执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.OPENAI.getValue(),
                AiTypeEnum.DRAW.getValue());
        String imgUrl= ""; // 大模型返回的结构
        boolean isSave = false; // 数据添加状态
        // 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                // 获取分布式锁失败
                return ResponseEntity.fail("请勿频繁请求，请稍后再试");
            }
//        调用 Open AI 接口
            ImageResponse result = imageModel.call(new ImagePrompt(question,
                    OpenAiImageOptions.builder()
                            .withHeight(1024)
                            .withWidth(1024).build()));

            imgUrl = result.getResult().getOutput().getUrl();
            //        保存数据在数据库中
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(imgUrl);
            answer.setModel(AiModelEnum.OPENAI.getValue());
            answer.setType(AiTypeEnum.DRAW.getValue());
            answer.setUid(uid);
            isSave = answerService.save(answer);
        } catch (Exception e) {
        } finally {
            rLock.unlock();
        }
        if(!isSave) {
//            保存失败
            return ResponseEntity.fail("数据保存失败，请重试");
        }
        return ResponseEntity.succ(imgUrl);
    }

    //调用 Open AI 历史对话查询记录
    @PostMapping("/getChatList")
    public ResponseEntity getChatList() {
        Long uid = SecurityUtil.getCurrentUser().getUid();
        int model = AiModelEnum.OPENAI.getValue();
        int type = AiTypeEnum.CHAT.getValue();
        String cacheKey = AppVariable.getListCacheKey(uid, model,type);
        Object list = redisTemplate.opsForValue().get(cacheKey);
        if(list == null)  {
            // 缓存不在
            QueryWrapper<Answer> wrapper = new QueryWrapper<>();
            wrapper.eq("uid",uid);
            wrapper.eq("type", type);
            wrapper.eq("model", model);
            wrapper.orderByDesc("aid");
            List<Answer> dataList = answerService.list(wrapper);
            // 存储在缓存中
            redisTemplate.opsForValue().set(cacheKey, dataList, 1, TimeUnit.DAYS);
            return ResponseEntity.succ(dataList);
        } else {
            return ResponseEntity.succ(list);
        }
    }

    //调用 Open AI 绘画历史查询记录
    @PostMapping("/getDrawList")
    public ResponseEntity getDrawList() {
        Long uid = SecurityUtil.getCurrentUser().getUid();
        int model = AiModelEnum.OPENAI.getValue();
        int type = AiTypeEnum.DRAW.getValue();
        String cacheKey = AppVariable.getListCacheKey(uid, model,type);
        Object list = redisTemplate.opsForValue().get(cacheKey);
        if(list == null)  {
            // 缓存不在
            QueryWrapper<Answer> wrapper = new QueryWrapper<>();
            wrapper.eq("uid",uid);
            wrapper.eq("type", type);
            wrapper.eq("model", model);
            wrapper.orderByDesc("aid");
            List<Answer> dataList = answerService.list(wrapper);
            // 存储在缓存中
            redisTemplate.opsForValue().set(cacheKey, dataList, 1, TimeUnit.DAYS);
            return ResponseEntity.succ(dataList);
        } else {
            return ResponseEntity.succ(list);
        }
    }
}
